package com.fh.service.impl;

import com.fh.mapper.OrderItemMapper;
import com.fh.mapper.OrdersMapper;
import com.fh.mapper.ProductSkuMapper;
import com.fh.mapper.ShoppingCartMapper;
import com.fh.model.OrderItem;
import com.fh.model.Orders;
import com.fh.model.ProductSku;
import com.fh.model.vo.ShoppingCartVO;
import com.fh.service.OrdersService;
import com.fh.utils.ResultState;
import com.fh.vo.ResultVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrdersServiceImpl implements OrdersService {
  @Resource
  private ShoppingCartMapper shoppingCartMapper;
 @Resource
 private OrdersMapper ordersMapper;
 @Resource
 private OrderItemMapper orderItemMapper;
 @Resource
 private ProductSkuMapper productSkuMapper;


    @Override
    @Transactional
    public Map<String,String> addOrders(String cids, Orders orders) {
        Map<String,String> map=new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String[] arr = cids.split(",");
        List<Integer> list=new ArrayList<>();
        for (String cid : arr) {
            list.add(Integer.parseInt(cid));
        }
        //查询库存
        List<ShoppingCartVO> shoppingCartVOS = shoppingCartMapper.selectCartByCartId(list);
       boolean stock=true;
       String  untitled="";
        for (ShoppingCartVO cartVO : shoppingCartVOS) {
            if (Integer.parseInt(cartVO.getCartNum())>cartVO.getStock()){
                stock=false;
                break;
            }
            untitled=untitled+cartVO.getProductName()+",";
        }
        if (stock){
      //保存订单
            orders.setUntitled(untitled.substring(0,untitled.length()-1));
            orders.setCreateTime(new Date());
            orders.setStatus("1");
            String orderId= UUID.randomUUID().toString().replace("-","");
            orders.setOrderId(orderId);
            ordersMapper.insert(orders);
      //生产商品快照
            List<OrderItem> orderItems=new ArrayList<>();
            for (ShoppingCartVO sc : shoppingCartVOS) {
               String orderItemId=UUID.randomUUID().toString();
                OrderItem orderItem=new OrderItem();
                orderItem.setItemId(orderItemId);
                orderItem.setOrderId(orderId);
                orderItem.setProductId(sc.getProductId());
                orderItem.setProductPrice(new BigDecimal(sc.getSellPrice()));
                orderItem.setBuyCounts(Integer.parseInt(sc.getCartNum()));
                orderItem.setSkuId(sc.getSkuId());
                orderItem.setProductImg(sc.getProductImg());
                orderItem.setTotalAmount(new BigDecimal(sc.getSellPrice()));
                orderItem.setSkuName(sc.getSkuName());
                orderItem.setBuyTime(new Date());
                orderItem.setIsComment(0);
                orderItem.setProductName(sc.getProductName());
                try {
                    orderItem.setBasketDate(sdf.parse(sc.getCartTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                orderItemMapper.insert(orderItem);
            }

          //减库存
            for (ShoppingCartVO cartVO : shoppingCartVOS) {
               int newStock=cartVO.getStock()-Integer.parseInt(cartVO.getCartNum());
                ProductSku productSku=new ProductSku();
                productSku.setSkuId(cartVO.getSkuId());
                productSku.setStock(newStock);
                productSkuMapper.updateByPrimaryKeySelective(productSku);
            }
         //删除购物车
            for (Integer cid : list) {
                shoppingCartMapper.deleteByPrimaryKey(cid);
            }

            map.put("orderId",orderId);
            map.put("productName",untitled.substring(0,untitled.length()-1));
            return  map;
        }
        else {
            return null;
        }
    }

    @Override
    public int updateOrderStatus(String orderId, String status) {
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        orders.setStatus(status);

        return ordersMapper.updateByPrimaryKeySelective(orders);
    }

    @Override
    public void closeOrder(String orderId) {
        Orders orders1=new Orders();
        orders1.setOrderId(orderId);
        orders1.setStatus("6");
        orders1.setCloseType(1);
        ordersMapper.updateByPrimaryKeySelective(orders1);
        //还原库存
        Example example1 = new Example(OrderItem.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("orderId",orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);
        for (OrderItem orderItem : orderItems) {
            ProductSku productSku = productSkuMapper.selectByPrimaryKey(orderItem.getSkuId());
            productSku.setStock(productSku.getStock()+orderItem.getBuyCounts());
            productSkuMapper.updateByPrimaryKeySelective(productSku);
        }
    }
}
